import traceback

from flask import Flask
from flask_cors import CORS

# from extensions.injector_extensions import register_dependency_injection
from init.server_load import load_config
from database.db_manager import get_session
from utils.log import log_api


class WebApplication(object):
    _host: str = None
    _port: int = None
    _app: Flask = None

    def __init__(self, host: str = "0.0.0.0", port: int = 5000, launch_type: str = 'main'):
        self._host = host
        self._port = port
        self.init_env()
        self.init_config()
        self.init_db()
        if launch_type == 'main':
            self.init_global_data()
            self.hook()
        # 依赖注入
        # register_dependency_injection(self._app)

    def init_env(self):
        """
        初始化服务器环境
        :return: None
        """
        from config.env.config_env import run_config

        self._app = Flask(__name__)
        CORS(self._app, supports_credentials=True)
        self._app.config["CORS_HEADERS"] = "Content-Type"
        self._app.config.from_object(run_config)

    def init_global_data(self):
        # init_weixin_token()
        # db_session = get_session()
        # try:
        #     init_wx_config(db_session)
        # except Exception as e:
        #     log_api.error(traceback.format_exc(15))
        # finally:
        #     if db_session is not None:
        #         db_session.close()
        pass


    def init_config(self):
        """
        加载服务器配置
        :return: None
        """
        from config import server_config

        load_config(self._app)
        self._port = server_config.web_port

    def init_db(self):
        pass

    def get_extentions(self, name):
        if name not in self._app.extensions:
            return None
        return self._app.extensions[name]

    def run(self):
        self._app.run(self._host, self._port)

    def hook(self):
        from forword.hook.request_hook import set_hook

        set_hook(self._app)

